#!/usr/bin/env python
# -*- coding: utf-8 -*

import curses


_tab_size = 4

class PointXY:
    """ Класс точки X,Y """
    def __init__(self,x=0,y=0):
        self.x=x
        self.y=y
    def __str__(self):
        return "%d:%d" % (self.x,self.y)

class Rectangle:
    """ Класс точки X,Y """
    def __init__(self,left=0,top=0,width=0,height=0):
        self.left=left
        self.top=top
        self.width=width
        self.height=height
    def __str__(self):
        return "(%d:%d:%d:%d)" % (self.left,self.top,self.width,self.height)


class TextProcessor:
    def __init__(self,text=[]):
	#print "!:%d" % text[5].find("\t")
	self.text = text #text.split("\n")
	self.cursor = PointXY(0,0)

    def screen_cursor(self):
	"""Получить/Установить курсор с учетом всех символов."""

	tmp = PointXY(self.cursor.x,self.cursor.y)
	if (tmp.x<0):tmp.x=0
	line = unicode(self.text[tmp.y],"UTF-8")
	
	#print "%s" % line
	line_tab = calc_tab(line)

	part_of_line = line[:tmp.x]
	res = PointXY(0,tmp.y)

	
	res.x=len(calc_tab(part_of_line)) #+int(len(part_of_line.split("\t"))-1)*(_tab_size-1)
	#res.x=len(line_tab)
	if (res.x>len(line_tab)): res.x = len(line_tab)-1
	return res

    def build(self,rect):
	zone = []
	for y in range(rect.height):
	    print y+rect.top
	    if (len(self.text)>int(y+rect.top)):
		
		line = unicode(calc_tab(self.text[y+rect.top]) ,"UTF-8")
		zone += [line[rect.left:rect.left+rect.width]]
	    else:
		#print "break"
		break
	return zone 

class PageProcessor:
    def __init__(self,scr_size=Rectangle(),processor=None):
	self.page = PointXY(0,0)
	self.scr_size = scr_size
	self.processor = processor
	self.cursor = PointXY(0,0)

    def build(self,scr):
	zonerect = Rectangle(self.page.x,self.page.y,self.scr_size.width,self.scr_size.height)
	zone = self.processor.build(zonerect)
	#print zone
	for y in range(len(zone)):
	    scr.addstr(y+self.scr_size.top,self.scr_size.left,zone[y].encode("UTF-8"))
	scr.refresh()
	
    def Cursor(self,scr):
	self.cursor = self.processor.screen_cursor()
	scr.move(self.cursor.y+self.scr_size.top,self.cursor.x+self.scr_size.left)
	
    
# Расчет табов
def pad(cnt,p=4):
    res = ""
    if cnt==0:cnt=4
    for i in range(cnt):
	res+=" "
    return res

def calc_tab(text):
    res=""
    args = text.split("\t")
    for i in range(len(args)) :
	if i==len(args)-1:
	    res+=args[i]
	else:
	    res+=args[i]+pad( len(args[i]) % 4 )

    return res
    